#!/usr/bin/python
"""

    svn_ignore_files.py
        
        helper file which reads a list of files to be ignored
        by svn from a configuration file
        
        parameters/IGNORED_FILES contains a list of files to
        be ignored (with relative paths)
        if [GLOBAL] is specified, this will be applied to
        all svn managed directories


#
#
#   Copyright (C) 2007 Leo Goodstadt
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; version 2
#   of the License
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""

from optparse import OptionParser
import os, sys, tempfile
import StringIO

# 
# 
# add python modules to search path
exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))



parser = OptionParser(version="%prog 1.0")
parser.add_option("-i", "--ignore_file_name", dest="ignorefile",
                  metavar="FILE",                       
                  type="string",
                  help="name and path of configuration file holding list of " +
                        "files to be ignored by svn")

parser.add_option("-v", "--verbose", dest = "verbose",
                  action="store_true", default=False,
                  help="Echo to shell.")

parser.set_defaults(ignorefile = os.path.join("parameters", 'IGNORED_FILES')) 

# get help string
f =StringIO.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, args) = parser.parse_args()



    
import general_util

#_______________________________________________________________________________

#   run svn_ignore

#_______________________________________________________________________________
def svn_ignore(directory, ignores, recursive = ''):
    '''
    Set svn:ignore for the specified directory

    Use all the parameters in ignores[directory]
    set recursive = true if necessary
    if ignores[directory] is empty, this parameter ignored

    Appends [GLOBAL] properties to every directory
    '''
    
    #
    # get temp file
    # 
    f = tempfile.NamedTemporaryFile(delete=False)
    file_name = f.name

    all_ignores = ignores.get(directory, set())
    if ignores.has_key('[GLOBAL]'):
        all_ignores = all_ignores.union(ignores['[GLOBAL]'])
        
    f.write("\n".join(list(all_ignores)))
    f.close()
    if recursive:
        recursive = '-R'
    os.system("svn propset svn:ignore %s -F '%s' %s 2&>/dev/null" % (recursive, file_name, directory))
    #os.system("cat %s" % file_name) 
    os.unlink(file_name)
    #print >>sys.stderr, file_name


#_______________________________________________________________________________

#   Read IGNORED_FILES from parameter directory

#_______________________________________________________________________________
my_path = os.path.abspath(".")
# 
#   check that can find IGNORED_FILES
# 
if not os.path.isfile(options.ignorefile):
    general_util.die_error("svn ignore file %s is missing!!" % (options.ignorefile))
elif options.verbose:
    sys.stderr.write("\n    Reading ignore files from %s\n\n" % options.ignorefile)

from collections import defaultdict

ignored_paths = defaultdict(set)
for line in file(options.ignorefile):
    line = line.rstrip()

    # ignore comments
    if not len(line) or line[0] == '#': continue


    # split into file and path    
    if '[GLOBAL]' in line:
        # this is a special symbol indicating that these apply to all directories
        (path, file) = os.path.split(line)
    else:
        # make paths relative to my directory
        full_path = os.path.abspath(os.path.join(my_path, line))
        (path, file) = os.path.split(full_path)
        
    #print (path, file)
    ignored_paths[path].add(file)
    
if options.verbose:
    print "    Files to ignore:"
    for path in sorted(ignored_paths):
        for file in ignored_paths[path]:
            sys.stderr.write("      %s:%s\n" % (path, file))

#
#   Sets global properties true for every directory
#
if ignored_paths.has_key('[GLOBAL]'):
    global_ignores = dict()
    global_ignores['[GLOBAL]'] = ignored_paths['[GLOBAL]']
    #debug
    #print "Global ignore:", ignored_paths['[GLOBAL]']
    svn_ignore(my_path, global_ignores, True)

#
#   Sets per directory property
#
for path in ignored_paths.keys():
    if path == '[GLOBAL]':
        continue
    svn_ignore(path, ignored_paths)


if options.verbose:
    sys.stderr.write("\n    Done\n\n")



